<template>
<view>
<!-- <import src="../../view-new/aikucun/aikucun_hot_product.wxml"/>    -->





<view class="container"> 
<view v-if="hasMore" class="hasMoreCart">刷新购物车查看商品</view> 
<block v-if="cartData">
  <checkbox-group @change="checkboxChange">
    <view class="cartContainer" v-for="(cartshop, index) in cartData" :key="index">
      <view class="cartShopName">{{cartshop.shopName}}</view>

      <view class="cartItems" v-for="(cart, index2) in cartshop.carItems" :key="index2" v-if="cart.count">
        <!-- 滑动块start -->
        <view class="slidingItem" @touchstart="touchS" @touchmove="touchM" @touchend="touchE" :data-index="index" :style="cart.txtStyle">
          <view class="deleteItem" :data-info="cart" @click.stop="deleById">
            <!-- <text>x</text> -->
            <image class="deleteItemImg" src="https://image1.sansancloud.com/aikucun/2018_03/21/19/33/25_702.jpg"></image>
          </view>
          <!-- 商品活动名start -->
          <view class="promotionBean" v-if="cart.item.promotionBean">
            <view class="promotionBean_line"></view>
            <view class="promotionBean_bg" :style="'background:' + setting.platformSetting.secondColor + ';'">
              <text class="promotionName">{{cart.item.promotionBean.name}}</text>
            </view>
          </view>
          <view v-else style="margin-top:20rpx"></view>
          <!-- 商品活动名end -->
          <!-- 商品信息start -->
          <view class="carItemsInfo">
            <label class="itemCheckbox">
              <checkbox :checked="checkedList" :color="setting.platformSetting.defaultColor" :value="cart.id"></checkbox>
            </label> 
            <image @click.stop="cart_pro_click_toDetailFun" :data-description="cart.item.promotionBean.description" :data-name="cart.item.name" :data-promotionId="cart.item.promotion" :data-productId="cart.item.productCode" :data-id="cart.item.id" class="itemCheckbox_image" mode="aspectFill" :src="cart.item.imagePath + '?x-oss-process=style/preview'"></image>
            <view class="item_infomation" @click.stop="cart_pro_click_toDetailFun" :data-description="cart.item.promotionBean.description" :data-name="cart.item.name" :data-promotionId="cart.item.promotion" :data-productId="cart.item.productCode" :data-id="cart.item.id">
              <view class="item_infomation_name" :data-info="cart" v-if="cart.count">{{cart.item.name}}</view>
              <view v-if="cart.count > cart.stock" class="cart_stock_warn font_red">
                库存不足，剩余库存（{{cart.stock}}）  
              </view>
              <view class="cart_infoMeasure">
                <view v-for="(mesure, index) in cart.measureCartensian.measurements" :key="index" class="cart_infoMeasure_name">{{mesure.measureName}}</view>
              </view>
              <view class="item_infomation_nums_cart_not_add"> 
                <view class="dellCart_butn_container_1" :style="'border:2rpx solid ' + setting.platformSetting.defaultColor">
                  <view class="carIcon" :data-id="index2" :data-cantadd="cart.count == 1" :data-count="cart.count" @click.stop="subCarNum">
                    <view class="addVertical" :style="'background:' + (cart.count == 1? '#aaa':setting.platformSetting.defaultColor)"></view>
                  </view>
                  <text class="flexCenter font1" :style="'color:' + setting.platformSetting.defaultColor + ';font-size:28rpx'">{{cart.count}}</text>
                  <view class="carIcon" :data-id="index2" :data-cantadd="cart.count == cart.stock" :data-count="cart.count" @click.stop="addCarNum">
                      <view :style="'background:' + (cart.count == cart.stock ? '#aaa':setting.platformSetting.defaultColor)" class="addCross"></view>
                      <view :style="'background:' + (cart.count == cart.stock ? '#aaa':setting.platformSetting.defaultColor)" class="addVertical"></view> 
                  </view>
                </view>
              </view>
              <view class="item_infomation_money" :style="'color:' + setting.platformSetting.defaultColor + ';font-size:28rpx'">
              ￥{{cart.carItemPrice}}
              <text v-if="cart.unitShow" style="color:#bbb;font-size:20rpx;margin-left:4rpx;letter-spacing:4rpx;">/{{cart.unitShow}}</text>
              </view>

            </view>
          </view>
          <!-- 商品信息end -->
        </view>
         <!-- 滑动块end -->
        <view :data-info="cart" @click.stop="deleById" class="delBtn" :style="'background:' + setting.platformSetting.defaultColor">
          <text>删除</text>
        </view>
      </view>
      <view class="butn_container">
        <view class="de" @tap="delectChecked">删除选中</view>
        <view :data-shopId="cartshop.id" @tap="delectAll">清空商品</view>
      </view>

    </view>
  </checkbox-group>
</block>
<block v-else>
  <view class="noCart">
    <view class="noCartImg">
      <image mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_3/29/14/38/47_424.jpg?x-oss-process=style/preview"></image>
      <text style="font-size:32rpx;margin-top:20rpx;color: #C0BFBF">购物车暂时没有商品</text>
    </view>
    <view class="toLook" :style="'background:linear-gradient(116deg,' + setting.platformSetting.secondColor + ' 0%,' + setting.platformSetting.defaultColor + ' 100%);'" @click.stop="toIndex">
      <text>去逛逛</text>
    </view>
  </view>
</block>
 <custom-page-index-component :receiveData="sendIndexData" v-if='sendIndexData' @resEvent="getCart"></custom-page-index-component> 
</view>
 <!-- <view class="hotProductContainer" @tap="closeCardShare">
    <custom-page-index-component :receiveData="sendIndexData" v-if='sendIndexData' @resEvent="getCart"></custom-page-index-component> 
   <component is="aikucun_new_title" error-data="...setting,sysWidth,loginUser:loginUser,title:'爆款推荐'"></component> 
    <component is="measure_card" :setting="showCount" :focusData="focusData" :byNowParams="byNowParams" :measurementJson="showShare"></component> 
    <component is="kefu" :loginUser="showKefu"></component>
  </view> -->



<view class="cart_buttomHeight"></view>
<view class="cart_buttom">
  <label class="chooseAll" @tap="chooseAll">
    <checkbox :checked="allchecked" :color="setting.platformSetting.defaultColor">全选</checkbox>
  </label>
  <view class="toJieSuan">
    <view class="toJieSuan_money">
      <view style="font-weight:blod;color:#333;font-size:32rpx">总计<text class="price" style="margin-left:26rpx">￥{{countPrice}}</text></view>
    </view>
    <view class="toJieSuan_butn" @tap="createOrder_carFun" :style="'background-image:linear-gradient(to right,' + setting.platformSetting.secondColor + ',' + setting.platformSetting.defaultColor + ');box-shadow:0px 0px 6px 0px ' + color + ';'">去结算</view>
  </view>
</view>


<view class="kefu_wx_huodong" v-if="showHongDong" catchtouchmove="doNothing">
  <view class="kefu_bg_zhezhao" @tap="closeHongDong"></view>
  <view class="kefu_wx_card_hongdong">
     <view class="name">请分开结算以下商品</view>
        <radio-group class="code_container" @change="chooseHuodong">
          <label class="radioItems" v-for="(item, index) in chooseArr" :key="index" :data-id="item.id">
            <radio :checked="index == 0" :value="item.id" :color="setting.platformSetting.defaultColor"></radio>
            <view class="code_item">{{item.name}}商品</view>
          </label>
        </radio-group>
        
        <view class="tips_buy_butn_container">
           <view class="backtoCart_butn" @tap="closeHongDong">返回购物车</view>
           <view :style="'background:' + setting.platformSetting.defaultColor" class="go_to_pay_butn" @tap="chooseActive">去结算</view>
        </view> 
  </view>
</view>

<!--  海报-->
   <!-- <posters :proId="proId" :shopId="shopId" :ewmImgUrl="qrCodeUrl" v-if="posterState" @closePoaster="getChilrenPoster"></posters> -->
</view>
</template>

<script>
// import { json2Form } from "../../static/public/json2Form";
// import posters from "../../view/partials/canvas/index";
// import componentTagCustompage from "../../view/partials/custom_page/index";

export default {
  data() {
    return {
      showShare: [],
      sendIndexData: null,
      setting: null,
      cartData: [],
      allchecked: false,
      loginUser: null,
      countPrice: 0,
      countGood: 0,
      pushItem: [],
      checkedItem: [],
      minCount: '1',
      maskLoad: false,
      //按钮loading
      showHongDong: false,
      //活动购买的时候

      /* 热销数据 */
      products: null,
      hotProduct: [],
      //规格信息
      showCount: false,
      focusData: null,
      measurementJson: null,
      //购买的参数
      bindType: 'addto',
      //加入购物车or直接下单
      focusIndex: 0,
      showKefu: false,
      hasMore: false,
      delBtnWidth: 120,
      listPro_passActive: {},
      CartParamWaitPost: {
        cartesianId: '0',
        productId: '',
        shopId: '',
        count: '',
        type: 'change'
      },

      /* 全部参数 */
      params: {
        page: 1,
        promotionId: "",
        productName: '',
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },

      /* 规格和加入购物车部分 */
      byNowParams: {
        productId: '',
        itemCount: 1,
        shopId: '',
        cartesianId: '0',
        orderType: ''
      },
      startX: "",
      chooseArr: "",
      checkedList: false,
      sysWidth: "",
      listEnd: false,
      bindBuy: "",
      carCount: "",
      proId: "",
      shopId: "",
      posterState: false,
      qrCodeUrl: ""
    };
  },
  props: {},

  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      sysWidth: getApp().globalData.sysWidth,
      loginUser: getApp().globalData.loginUser,
      setting: getApp().globalData.setting
    });
    let sendIndexData = JSON.stringify({
      title: 'noTitle',
      url: "shoppingcard",
      params: {}
    });
    this.setData({
      sendIndexData: sendIndexData
    });
    this.getCart();
    // this.getHotProduct();
    this.getQrCode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  onShow: function () {
    if (!!getApp().globalData.loginUser) {
      this.setData({
        loginUser: getApp().globalData.loginUser
      });
    }

    this.setData({
      maskLoad: false
    });

    if (this.openShow) {
      this.getCart();
    }

    this.openShow = true;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCart();
    // this.getHotProduct();
    this.setData({
      hasMore: false
    });
    this.params.onPullDownRefresh = true; // 组件内的事件

    this.selectComponent('#productLists').getHotProduct(1, this.params.onPullDownRefresh);
    let that = this;
    setTimeout(function () {
      that.params.onPullDownRefresh = true;
    }, 500);
    wx.stopPullDownRefresh();
  },

  /* 分享 */
  onShareAppMessage: function (res) {
    if (res.from == "button") {
      console.log(res); // 商品id

      let id = res.target.dataset.id;
      let products = this.hotProduct;
      console.log("this.data.products", this.hotProduct);
      let index = 0;

      for (let i = 0; i < products.length; i++) {
        if (products[i].id == id) {
          console.log(products[i], i);
          index = i;
        }
      }

      let focusData = products[index];
      let imageUrl = focusData.imagePath;
      let shareName = '活动价：￥' + focusData.price + '(原价：￥' + focusData.tagPrice + ')' + focusData.brandName + focusData.name;
      let shareParams = {};
      shareParams.productName = focusData.productCode;
      console.log('nnnnnnnnnn' + shareName);
      shareParams.id = id;
      console.log("shareParams", shareParams);
      return getApp().globalData.shareForFx2('promotion_products', shareName, shareParams, imageUrl);
    } else {
      // 分享页面
      console.log("分享页面");
      return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
    }
  },
  onReachBottom: function () {
    var that = this; // 商品数目过多会导致setData的失败，setData有最大数目所以加载8页

    if (that.params.totalSize > that.params.curPage * that.params.pageSize && that.params.page < 8) {
      that.params.page++;
      // that.getHotProduct(); // 组件内的事件

      // this.selectComponent('#productLists').getHotProduct(that.params.page);
    }

    this.setData({
      listEnd: true
    });
  },
  methods: {
    touchS: function (e) {
      console.log('===touchS===', e);

      if (e.touches.length == 1) {
        this.setData({
          //设置触摸起始点水平方向位置
          startX: e.touches[0].clientX
        });
      }
    },
    touchM: function (e) {
      console.log('===touchM===', e);

      if (e.touches.length == 1) {
        //手指移动时水平方向位置
        var moveX = e.touches[0].clientX; //手指起始点位置与移动期间的差值

        var disX = this.startX - moveX;
        var delBtnWidth = this.delBtnWidth;
        var txtStyle = "";

        if (disX == 0 || disX < 0) {
          //如果移动距离小于等于0，文本层位置不变
          txtStyle = "left:0rpx";
        } else if (disX > 0) {
          //移动距离大于0，文本层left值等于手指移动距离
          txtStyle = "left:-" + disX + "rpx";

          if (disX >= delBtnWidth) {
            //控制手指移动距离最大值为删除按钮的宽度
            txtStyle = "left:-" + delBtnWidth + "rpx";
          }
        } //获取手指触摸的是哪一项


        var index = e.currentTarget.dataset.index;
        var list = this.cartData;
        list[0].carItems[index]['txtStyle'] = txtStyle; //更新列表的状态

        this.setData({
          cartData: list
        });
      }
    },
    touchE: function (e) {
      console.log('===touchE===', e);

      if (e.changedTouches.length == 1) {
        //手指移动结束后水平位置
        var endX = e.changedTouches[0].clientX; //触摸开始与结束，手指移动的距离

        var disX = this.startX - endX;
        var delBtnWidth = this.delBtnWidth; //如果距离小于删除按钮的1/2，不显示删除按钮

        var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "rpx" : "left:0rpx"; //获取手指触摸的是哪一项

        var index = e.currentTarget.dataset.index;
        var list = this.cartData;
        list[0].carItems[index]['txtStyle'] = txtStyle; //更新列表的状态

        this.setData({
          cartData: list
        });
        console.log('=list=', this.cartData);
      }
    },
    toProductDetail: function (e) {
      let info = e.currentTarget.dataset.info;
      wx.navigateTo({
        url: '/pages/productDetail/index?id=' + info.productId + "&addShopId=" + info.belongShop
      });
    },

    /* 编辑购物车 */
    closeOldEdit: function (index) {
      let cartData = this.cartData;
      let focusCart = cartData[0].carItems[index];
      focusCart.showEditView = false;
      this.setData({
        cartData: cartData
      });
    },
    editCart: function (e) {
      let index = e.currentTarget.dataset.index;

      if (this.oldEditIndex == -1) {} else {
        this.closeOldEdit(this.oldEditIndex);
      }

      this.oldEditIndex = index;
      let cartData = this.cartData;
      let focusCart = cartData[0].carItems[index];
      focusCart.showEditView = true;
      focusCart.count2 = focusCart.count;
      this.CartParamWaitPost.cartesianId = focusCart.measureCartesianId;
      this.CartParamWaitPost.productId = focusCart.productId;
      this.CartParamWaitPost.shopId = focusCart.belongShop;
      this.CartParamWaitPost.count = focusCart.count;
      this.CartParamWaitPost.type = 'change';
      this.setData({
        cartData: cartData
      });
    },
    sureChange: function (e) {
      // let index = e.currentTarget.dataset.index;
      let cartData = this.cartData; // let focusCart = cartData[0].carItems[index]
      // focusCart.showEditView = false

      console.log(this.CartParamWaitPost);
      this.postParams(this.CartParamWaitPost);
      this.setData({
        cartData: cartData
      });
    },
    _watchBigImageFun: function (e) {
      let urls = e.currentTarget.dataset.urls;
      let _url = e.currentTarget.dataset.url;
      let url = urls[0];

      if (!urls) {
        url = _url;
      }

      getApp().globalData.lookBigImage(url, urls);
    },

    /* 右上删除 */
    deleById: function (e) {
      let that = this;
      let info = e.currentTarget.dataset.info;
      let listPro = {};
      listPro.shopId = info.belongShop;
      listPro.selectedIds = info.id;
      wx.showModal({
        title: '提示',
        content: '删除该商品',
        success: function (res) {
          if (res.confirm) {
            that.delectCart(listPro);
          } else if (res.cancel) {
            return;
          }
        }
      });
    },

    /* 全部删除 */
    delectAll: function (e) {
      var that = this;
      console.log("====delectAll====", e);
      var listPro = {
        shopId: '',
        selectedIds: '',
        type: 'shopall'
      };
      listPro.shopId = e.currentTarget.dataset.shopid;
      wx.showModal({
        title: '提示',
        content: '全部删除',
        success: function (res) {
          if (res.confirm) {
            that.delectCart(listPro);
          } else if (res.cancel) {}
        }
      });
    },

    /* 删除选中 */
    delectChecked: function () {
      var that = this;
      var pushItem = this.pushItem;
      var listPro = {
        shopId: '',
        selectedIds: '',
        type: 'selected'
      };

      if (pushItem.length == 0) {
        return;
      }

      for (let i = 0; i < pushItem.length; i++) {
        listPro.shopId = pushItem[i].belongShop;
        listPro.selectedIds += pushItem[i].id + ',';
      }

      wx.showModal({
        title: '提示',
        content: '确认删除',
        success: function (res) {
          if (res.confirm) {
            that.delectCart(listPro);
          } else if (res.cancel) {}
        }
      });
    },
    //删除购物车的调用函数
    delectCart: function (params) {
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/delete_shopping_car_list_item.html", params, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('-----------delect----------');
          console.log(res.data);
          wx.hideLoading();
          that.getCart();
        },
        fail: function (res) {
          wx.hideLoading();
        }
      });
    },

    /* 购物车操作  */
    createOrder_carFun: function () {
      console.log('=====ss------');

      if (!getApp().globalData.checkShopOpenTime()) {
        console.log('=====kong------');
        return;
      }

      if (this.maskLoad) {
        console.log('mask');
        return;
      }

      console.log('=====tt------');
      var listPro = {
        shopId: '',
        selectedIds: ''
      };
      var pushItem = this.pushItem;

      if (pushItem.length == 0) {
        wx.showToast({
          title: '请选择下单商品',
          image: '/wxcomponents/images/icons/tip.png',
          duration: 2000
        });
        return;
      }

      for (let i = 0; i < pushItem.length; i++) {
        listPro.shopId = pushItem[i].belongShop;
        listPro.selectedIds += pushItem[i].id + ',';
      } 
      getApp().globalData.showToastLoading('loading', true);
      this.setData({
        maskLoad: true
      });
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/list_promotions_by_car_items.html", listPro, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'post',
        success: function (res) {
          console.log('------这里应该有promotionId数组--------');
          console.log(res.data);
          wx.hideLoading();

          if (res.data.length && res.data[0].id) {
            if (res.data.length == 1) {
              listPro.promotionId = res.data[0].id;
              that.createOrder22_carFun(listPro);
            } else {
              that.listPro_passActive = listPro;
              that.checkedActive = res.data[0].id;
              that.setData({
                showHongDong: true,
                chooseArr: res.data
              });
            }
          } else {
            listPro.promotionId = '0';
            that.createOrder22_carFun(listPro);
          }
        },
        fail: function (res) {
          wx.hideLoading();
          that.setData({
            maskLoad: false
          });
          getApp().globalData.loadFail();
        }
      });
    },

    /* 选择活动 */
    closeHongDong: function () {
      this.setData({
        showHongDong: false,
        maskLoad: false
      });
    },
    //选择的活动radio
    chooseHuodong: function (e) {
      this.checkedActive = e.detail.value;
    },
    chooseActive: function (e) {
      console.log('----kong----');

      if (this.checkedActive == -1) {
        return;
      }

      let id = this.checkedActive;
      console.log('选择的id', id);
      let listPro = this.listPro_passActive;
      listPro.promotionId = id;
      console.log(listPro);
      this.createOrder22_carFun(listPro);
    },

    /* 创建订单 */
    createOrder22_carFun: function (o) {
      var customIndex = getApp().globalData.AddClientUrl("/shopping_car_list_item_create_order.html", o, 'post');
      var that = this; // wx.showLoading({
      //   title: 'loading',
      //   mask: true
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res);

          if (res.data && res.data.orderNo) {
            wx.navigateTo({
              url: '/pages/edit_order/index?orderNo=' + res.data.orderNo
            });
          } else if (!res.data) {
            wx.showToast({
              title: '出错了,请刷新后重试',
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
            that.setData({
              maskLoad: false
            });
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 2000
            });
            that.setData({
              maskLoad: false
            });
          }

          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
          that.setData({
            maskLoad: false
          });
        },
        complete: function () {}
      });
    },

    /* 加入購物車 */
    subCarNum: function (e) {
      console.log('=====e=====', e);
      let that = this;
      let index = e.currentTarget.dataset.id;
      let focusCartItem = this.cartData[0].carItems[index];

      if (e.currentTarget.dataset.count == 1) {
        return;
      }

      let params = {
        cartesianId: '0',
        productId: '',
        shopId: '',
        secretCode: '',
        count: '',
        type: ''
      };
      params.cartesianId = focusCartItem.measureCartesianId;
      params.productId = focusCartItem.productId;
      params.shopId = focusCartItem.belongShop;
      params.secretCode = "sansan";

      if (focusCartItem.count == 1) {
        console.log(focusCartItem);
        params.count = 0;
        params.type = 'change';
      } else {
        params.count = 1;
        params.type = 'dec';
      }

      this.postParams(params, focusCartItem);
    },
    addCarNum: function (e) {
      let that = this;
      console.log("addCarNum",e)
      let index = e.currentTarget.dataset.id;
      let focusCartItem = this.cartData[0].carItems[index];
      let params = {
        cartesianId: '0',
        productId: '',
        shopId: '',
        secretCode: '',
        count: '',
        type: ''
      };
      params.cartesianId = focusCartItem.measureCartesianId;
      params.productId = focusCartItem.productId;
      params.shopId = focusCartItem.belongShop;
      params.secretCode = "sansan";
      params.count = 1;
      params.type = 'add';
      this.postParams(params, focusCartItem);
    },
    postParams: function (data, focusCartItem) {
      var that = this;

      if (!focusCartItem) {
        focusCartItem = 0;
      }

      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      console.log("customIndex.params",customIndex.params)
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);
          wx.hideLoading();

          if (res.data.id) {
            if (focusCartItem) {
              focusCartItem.count = res.data.count;
            }
          } else if (res.data.errcode == '-1') {
            getApp().globalData.echoErr(res.data.errMsg);
          }

          that.getCart();
        },
        fail: function (res) {
          wx.hideLoading();
        }
      });
    },

    /* 加载购物车内容 */
    getCart: function () {
      console.log('==========');
      var customIndex = getApp().globalData.AddClientUrl("/get_shopping_car_list_item.html");
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('------error-------');
          console.log("加载的数据", res.data);

          if (res.data.errcode == '10001') {
            that.setData({
              cartData: null
            });
            getApp().globalData.loadLogin();
          } else if (res.data.result.errcode == '-1') {
            that.setData({
              cartData: null
            });
            getApp().globalData.echoErr(res.data.result.errMsg);
          } else {
            if (!res.data.result || res.data.result.length == 0) {
              that.setData({
                cartData: null
              });
            } else if (res.data.result.errcode) {
              that.setData({
                cartData: null
              });
              getApp().globalData.echoErr(res.data.result.errMsg);
            } else {
              that.setData({
                cartData: res.data.result,
                allchecked: false,
                checkedList: false
              });
            }

            that.showPrice();
          } //wx.hideLoading()

        },
        fail: function (res) {// wx.hideLoading()
        }
      });
    },
    checkboxChange: function (e) {
      console.log('--------checkBox------');
      console.log(e.detail.value, 'value+++');
      var checkedItem = e.detail.value;
      console.log(checkedItem, 'checkedItem--------'); //加入选中标识

      let cartData = this.cartData[0].carItems;
      console.log(cartData, 'cartData+++');

      if (checkedItem.length == cartData.length) {
        this.setData({
          allchecked: true
        });
      } else {
        this.setData({
          allchecked: false
        });
      }

      this.setData({
        checkedItem: checkedItem
      });
      this.showPrice();
    },
    chooseAll: function (e) {
      if (!this.cartData) {
        return;
      }

      var checkedItem = [];
      console.log(this.allchecked);
      console.log(this.cartData[0].carItems);

      if (!this.allchecked) {
        for (let i = 0; i < this.cartData[0].carItems.length; i++) {
          let cartId = this.cartData[0].carItems[i].id.toString();
          checkedItem.push(cartId);
        }

        console.log(checkedItem, "执行了");
        this.setData({
          checkedList: true
        });
      } else {
        checkedItem.length = 0;
        this.setData({
          checkedList: false
        });
      }

      this.setData({
        checkedItem: checkedItem,
        allchecked: !this.allchecked
      });
      console.log(checkedItem, 'checkedItem+++');
      this.showPrice();
    },
    showPrice: function () {
      if (!this.cartData) {
        this.setData({
          countGood: 0,
          countPrice: 0
        });
        return;
      }

      var checkedItem = this.checkedItem;
      var cartDataItem = this.cartData[0].carItems;
      var pushItem = [];
      var countGood = 0;
      var countPrice = 0;

      for (let i = 0; i < cartDataItem.length; i++) {
        for (let j = 0; j < checkedItem.length; j++) {
          if (cartDataItem[i].id == checkedItem[j]) {
            pushItem.push(cartDataItem[i]);
          }
        }
      }

      for (let i = 0; i < pushItem.length; i++) {
        countGood += parseInt(pushItem[i].count);
        countPrice += parseInt(pushItem[i].count) * pushItem[i].carItemPrice;
      }

      countPrice = countPrice.toFixed(2);
      this.setData({
        pushItem: pushItem,
        countGood: countGood,
        countPrice: countPrice
      });
      console.log(pushItem, 'pushItem__');
      console.log(countGood, 'countGood__');
      console.log(countPrice, "countPrice__");
    },
    // 获取热销数据
    getHotProduct: function () {
      let param = {
        page: this.params.page
      };
      var customIndex = getApp().globalData.AddClientUrl("/more_product_list.html", param, 'get', '1');
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          that.params.pageSize = res.data.pageSize;
          that.params.curPage = res.data.curPage;
          that.params.totalSize = res.data.totalSize;

          if (that.hotProduct && that.hotProduct.length != "0") {
            let products = that.hotProduct;
            products = products.concat(res.data.result);
            that.setData({
              hotProduct: products
            });
          } else {
            that.setData({
              hotProduct: res.data.result
            });
          }

          console.log("主页面获取热销数据总", that.hotProduct);
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        }
      });
    },
    //点击购物车中的商品，跳转到详情页面
    cart_pro_click_toDetailFun: function (e) {
      console.log("点击购物车中的商品，跳转到详情页面");
      console.log(e.currentTarget.dataset.id);
      console.log(e.currentTarget.dataset);
      let promotionId = e.currentTarget.dataset.promotionid;
      let productId = e.currentTarget.dataset.id;
      console.log(e);
      console.log("============productId", productId);
      let description = e.currentTarget.dataset.description;

      if (!description || description == "undefined") {
        description = "";
      }

      let name = e.currentTarget.dataset.name;
      wx.navigateTo({
        url: '/pages/productDetail/index?id=' + productId + "&addShopId=0"
      });
    },

    /* 处理热销 */
    //切割数组
    sliceArray: function (array, size) {
      var result = [];

      if (!array) {
        return result;
      }

      for (let x = 0; x < Math.ceil(array.length / size); x++) {
        let start = x * size;
        let end = start + size;
        result.push(array.slice(start, end));
      }

      return result;
    },
    //获取图片数组 用来预览用
    getImageUrlList: function (array) {
      let result = [];

      if (!array) {
        return result;
      }

      for (let x = 0; x < array.length; x++) {
        result.push(array[x].imagePath);
      }

      return result;
    },
    sliceProductImageList: function (arr) {
      let that = this;

      for (let i = 0; i < arr.length; i++) {
        arr[i].imageListArr = that.sliceArray(arr[i].itemImages, 4);
        arr[i].imageListWatcher = that.getImageUrlList(arr[i].itemImages);
        arr[i].showShare = false; //显示分享
      }

      return arr;
    },
    //处理图片，只要四张
    dellProductImage: function (products) {
      let productsResult = this.sliceProductImageList(products);
      this.setData({
        products: productsResult
      });
    },

    /* 热销操作 */
    //点击 ...  显示分享
    showCardShare: function (e) {
      let oldIndex = this.focusIndex;
      let index = e.currentTarget.dataset.index;
      let products = this.products;
      let focusData = products;
      let showShare = this.showShare;

      if (oldIndex == index) {
        focusData[index].showShare = !focusData[index].showShare;
        showShare[index] = !showShare[index];
      } else {
        this.closeCardShare(oldIndex);
        focusData[index].showShare = !focusData[index].showShare;
        showShare[index] = !showShare[index];
      }

      console.log('--------1--------' + index, showShare);
      console.log("focusData", focusData);
      this.setData({
        products: focusData,
        focusIndex: index,
        showShare: showShare
      });
    },
    //关闭 ... 
    closeCardShare: function (oldIndex) {
      let index = this.focusIndex;

      if (!isNaN(oldIndex) && oldIndex > -1) {
        index = oldIndex;
      }

      console.log('--------2--------' + index);

      if (index == -1) {
        return;
      }

      let products = this.hotProduct;
      console.log("hotProduct", this.hotProduct);
      let focusData = products;

      if (focusData[index].showShare == false) {
        return;
      }

      focusData[index].showShare = false;
      this.setData({
        hotProduct: products
      });
    },
    //开关显示客服的
    showKefuWechatCode: function (e) {
      let index = e.currentTarget.dataset.index;
      this.closeCardShare(index);
      this.setData({
        showKefu: true
      });
    },
    //查看客服里面的二维码
    lookBigWxCode: function (e) {
      let url = e.currentTarget.dataset.url;

      if (!url) {
        return;
      }

      let urls = [];
      urls.push(url);
      wx.previewImage({
        current: url,
        // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表

      });
    },
    closeKefu: function () {
      this.setData({
        showKefu: false
      });
    },
    //看大图
    watchBigImage: function (e) {
      let urls = e.currentTarget.dataset.urls;
      let myurl = e.currentTarget.dataset.me;
      console.log(urls);
      wx.previewImage({
        current: myurl,
        // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表

      });
    },
    subNum: function () {
      if (this.measurementJson.id) {
        this.setData({
          minCount: this.measurementJson.minSaleCount
        });
      } else {
        this.setData({
          minCount: 1
        });
      }

      if (this.byNowParams.itemCount == this.minCount) {
        return;
      }

      this.byNowParams.itemCount--;
      this.setData({
        byNowParams: this.byNowParams
      });
    },
    addNum: function (e) {
      let cantadd = e.currentTarget.dataset.cantadd;

      if (cantadd == 1) {
        return;
      } else {
        this.byNowParams.itemCount++;
        this.setData({
          byNowParams: this.byNowParams
        });
      }
    },
    selectFun: function (data) {
      let that = this;
      console.log('===selectFun====', data);
      let typeData = data.detail.sendData.type;
      let reqdata = data.detail.sendData.data;

      if (typeData == 'addCat') {
        that.bindBuyFun(reqdata);
      } else if (typeData == 'getProData') {
        that.resProData(reqdata);
      }
    },
    //点击加入购物车或立即下单
    bindBuyFun: function (e) {
      console.log(e);
      let index = e.index;
      let bindBuy = e.bindbuy;
      console.log('this.data.hotProduct', this.hotProduct);
      let products = this.hotProduct;
      let focusData = e.info;
      this.byNowParams.productId = focusData.id;
      this.byNowParams.shopId = focusData.belongShopId;
      this.byNowParams.orderType = 0;
      this.chooseMeasureItem(focusData);
      console.log(focusData);
      this.setData({
        focusData: focusData,
        showCount: true,
        byNowParams: this.byNowParams,
        bindBuy: bindBuy
      });
    },
    buyNow: function () {
      console.log(this.byNowParams);

      if (!getApp().globalData.checkShopOpenTime()) {
        return;
      }

      if (!getApp().globalData.checkIfLogin()) {
        return;
      } //立即购买


      if (this.bindBuy == 'addto') {
        console.log('加入购物车'); //addto

        this.addtocart();
      } else {
        console.log('立即购买');
        this.createOrder22(this.byNowParams);
      }
    },

    /* 加入購物車 */
    addtocart: function () {
      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      var params = {
        cartesianId: '',
        productId: '',
        shopId: '',
        count: '',
        type: ''
      };

      if (!this.focusData.measureItem || this.focusData.measureTypes.length == 0) {
        params.cartesianId = '0';
      } else {
        params.cartesianId = this.measurementJson.id;
      }

      params.productId = this.focusData.id;
      params.shopId = this.focusData.belongShopId;
      params.count = this.byNowParams.itemCount;
      params.type = 'add';
      this.postParams_hotFun(params);
    },
    postParams_hotFun: function (data) {
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('---------------change_shopping_car_item-----------------');
          console.log(res.data);
          wx.hideLoading();

          if (that.bindType == 'addto') {
            that.setData({
              showCount: false
            });
          }

          if (res.data.productId && res.data.productId != 0) {
            that.setData({
              carCount: res.data.totalCarItemCount
            });

            if (data.count == 0) {
              console.log('通过加入购物车来确定购物车里面的商品数量');
            } else {
              wx.showToast({
                title: '加入购物车成功'
              });
              that.setData({
                hasMore: true
              });
            }
          } else {
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 3000
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 创建订单 */
    createOrder22: function (o) {
      var customIndex = getApp().globalData.AddClientUrl("/buy_now.html", o, 'post');
      var that = this; // wx.showLoading({
      //   title: 'loading',
      //   mask: true
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res);

          if (!!res.data.orderNo) {
            wx.hideLoading();
            wx.navigateTo({
              url: '/pages/edit_order/index?orderNo=' + res.data.orderNo
            });
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.data.errMsg,
              image: '/wxcomponents/images/icons/tip.png',
              duration: 3000
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function (res) {}
      });
    },
    closeZhezhao: function () {
      this.MeasureParams = [];
      this.setData({
        showCount: false,
        focusData: null
      });
    },
    //提交规格产品
    // submitMeasure: function (id) {
    //   var that = this
    //   let focusProduct = this.data.focusData
    //   let measurementJson = this.data.measurementJson
    //   let data = {}
    //   data.cartesianId = measurementJson.id
    //   data.productId = focusProduct.id
    //   data.shopId = focusProduct.belongShopId
    //   data.count = 1
    //   data.type = 'add'
    //   var customIndex = app.AddClientUrl("/change_shopping_car_item.html", data, 'post')
    //   wx.request({
    //     url: customIndex.url,
    //     data: customIndex.params,
    //     header: app.headerPost,
    //     method: 'POST',
    //     success: function (res) {
    //       console.log('--------add----------')
    //       console.log(res.data)
    //     },
    //     fail: function (res) {
    //       app.loadFail()
    //     },
    //     complete: function () {
    //       wx.hideLoading()
    //     }
    //   })
    // },
    //获取规格价格参数
    get_measure_cartesionFun: function () {
      this.setData({
        measurementJson: {
          waitDataState: false
        }
      });
      this.byNowParams.cartesianId = -1;
      let productId = this.focusData.id;
      let postStr = '';

      if (!this.focusData.measureItem || this.MeasureParams.length == 0) {
        this.byNowParams.cartesianId = '0';
        this.setData({
          measurementJson: {
            waitDataState: true
          }
        }); //没有规格时 不需要等待请求

        return;
      }

      for (let i = 0; i < this.MeasureParams.length; i++) {
        postStr += this.MeasureParams[i].value + ',';
      }

      let param = {};
      param.productId = productId;
      param.measureIds = postStr;
      let customIndex = getApp().globalData.AddClientUrl("/get_measure_cartesion.html", param);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          if (!res.data.id) {
            // 没有这个参数
            //......
            console.log('error'); //.....
          }

          console.log(res.data);
          that.byNowParams.cartesianId = res.data.id;
          that.setData({
            measurementJson: res.data
          });
          that.measurementJson.waitDataState = true;
          that.setData({
            measurementJson: that.measurementJson
          });
          that.byNowParams.itemCount = that.measurementJson.minSaleCount;
          that.setData({
            byNowParams: that.byNowParams
          });
          that.setData({
            minCount: that.byNowParams.itemCount
          });
          console.log('minCount', that.minCount);
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },

    /* 初始化 选规格 */
    chooseMeasureItem: function (focusData) {
      console.log('----------初始化规格参数-----------');

      if (!focusData.measureItem) {
        return;
      }

      for (let i = 0; i < focusData.measureTypes.length; i++) {
        focusData.measureTypes[i].checkedMeasureItem = 0; //初始化选择的数据

        let param = {};
        param.name = focusData.measureTypes[i].name;
        param.value = focusData.measureTypes[i].productAssignMeasure[0].id;
        this.MeasureParams.push(param);
      }

      this.setData({
        focusData: focusData
      });
      this.get_measure_cartesionFun();
    },
    //选择规格小巷的---显示
    radioChange: function (e) {
      let index = e.currentTarget.dataset.index;
      let indexJson = getApp().globalData.getSpaceStr(index, '-'); //console.log(indexJson)

      let focusData = this.focusData;
      focusData.measureTypes[indexJson.str1].checkedMeasureItem = indexJson.str2;
      this.setData({
        focusData: focusData
      });
    },
    //选择规格小巷---获取数据
    chooseMeasure: function (e) {
      console.log(e.detail.value);
      let chooseMeasureJson = getApp().globalData.getSpaceStr(e.detail.value, '-');
      console.log(chooseMeasureJson);

      for (let i = 0; i < this.MeasureParams.length; i++) {
        if (this.MeasureParams[i].name == chooseMeasureJson.str1) {
          this.MeasureParams[i].value = chooseMeasureJson.str2;
        }
      }

      this.get_measure_cartesionFun();
    },
    // 跳转到详情页
    tolinkUrl: function (e) {
      console.log(e);
      var a = "product_detail.html?productId=" + e.currentTarget.dataset.id;
      getApp().globalData.linkEvent(a);
    },
    // 跳转到首页
    toIndex: function () {
      getApp().globalData.toIndex();
    },

    // 展示海报
    showPosters(e) {
      console.log("showPostersEEEE", e.detail.e.currentTarget.dataset.id);
      let that = this;
      this.setData({
        proId: e.detail.e.currentTarget.dataset.id,
        shopId: "236",
        posterState: true
      });
    },

    // 关闭海报
    getChilrenPoster(e) {
      let that = this;
      that.setData({
        posterState: false
      });
    },

    // 获取二维码
    getQrCode: function () {
      let userId = "";

      if (getApp().globalData.loginUser && getApp().globalData.loginUser.platformUser) {
        userId = 'MINI_PLATFORM_USER_ID_' + getApp().globalData.loginUser.platformUser.id;
      }

      console.log("app.loginUser.platformUser", getApp().globalData.loginUser.platformUser.id); // path=pageTab%2findex%2findex%3fAPPLY_SERVER_CHANNEL_CODE%3d'

      let postParam = {};
      postParam.SHARE_PRODUCT_DETAIL_PAGE = this.proId;
      postParam.scene = userId; // 上面是需要的参数下面的url

      var customIndex = getApp().globalData.AddClientUrl("/super_shop_manager_get_mini_code.html?path=pageTab%2findex%2findex%3fSHARE_PRODUCT_DETAIL_PAGE%3d" + this.proId + "%26scene%3d" + userId, postParam, 'get', '1');
      var result = customIndex.url.split("?");
      customIndex.url = result[0] + "?" + result[1];
      console.log("customIndex", customIndex.url, result[0]);
      var that = this;
      that.setData({
        qrCodeUrl: customIndex.url
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>